<template>
  <div class="cropper-content">
    <div class="choose-img-btn-wrap">
      <label class="choose-img-btn" for="uploads">选择图片</label>
      <input
        ref="selector"
        type="file"
        id="uploads"
        style="position: absolute; clip: rect(0 0 0 0)"
        accept="image/png, image/jpeg, image/gif, image/jpg"
        @change="selectImg($event)"
      />
      <span v-if="option.limitSize !== false" class="tips"
        >图片尺寸大小限定{{ option.autoCropWidth }}X{{ option.autoCropHeight }}px</span
      >
    </div>
    <div style="display: flex; flex-direction: row; flex-wrap: nowrap">
      <div style="width: 66%; height: 300px">
        <vue-cropper
          ref="cropper"
          mode="cover"
          :img="option.img"
          :output-size="option.size"
          :output-type="option.outputType"
          :info="true"
          :full="option.full"
          :fixed="fixed"
          :can-move="option.canMove"
          :can-move-box="option.canMoveBox"
          :fixed-box="option.fixedBox"
          :original="option.original"
          :auto-crop="option.autoCrop"
          :auto-crop-width="option.autoCropWidth"
          :auto-crop-height="option.autoCropHeight"
          :center-box="option.centerBox"
          :high="option.high"
          :max-img-size="option.max"
          @real-time="realTime"
          @img-load="imgLoad"
        />
      </div>
      <!--预览效果图-->
      <div
        :style="{
          position: 'relative',
          width: '34%',
          height: '300px',
          overflow: 'hidden',
          border: '1px dashed #cccccc',
          margin: '0 0 0 10px',
        }"
      >
        <div
          :style="{
            position: 'absolute',
            top: 0,
            right: 0,
            bottom: 0,
            left: 0,
            margin: 'auto',
            width: previews.w + 2 + 'px',
            height: previews.h + 2 + 'px',
            overflow: 'hidden',
            ...previews.div,
          }"
        >
          <img :src="previews.url" :style="previews.img" />
        </div>
      </div>
    </div>
    <!--底部操作工具按钮-->
    <div class="footer-btn">
      <a-button type="primary" @click="rotateLeft"><a-icon type="left" />左旋转</a-button>
      <a-button type="primary" @click="rotateRight">右旋转<a-icon type="right" /></a-button>
      <a-button type="primary" @click="refreshCrop"> ↻ </a-button>
      <div class="upload-btn">
        <a-button type="primary" @click="uploadImg('blob')">保存修改</a-button>
      </div>
    </div>
  </div>
</template>

<script>
import 'vue-cropper/dist/index.css';

import { merge } from 'lodash-es';
import { VueCropper } from 'vue-cropper';
import { uploadFiles, faceCheck } from '../../api/index.js';

export default {
  name: 'cropper-img',
  components: { VueCropper },
  props: {
    type: { type: String, default: '/people/head' },
    faceCheck: { type: Boolean, default: false }, //人脸验证
    setting: { type: Object, default: () => ({}) },
  },
  data() {
    return {
      previews: {},
      show: true,
      fixed: false,
      basicOption: {
        img: '',
        size: 1,
        full: false,
        outputType: 'png',
        limitSize: true,
        canMove: true,
        fixedBox: false,
        original: false,
        canMoveBox: true,
        autoCrop: true,
        // 只有自动截图开启 宽度高度才生效
        autoCropWidth: 160,
        autoCropHeight: 150,
        centerBox: false,
        high: true,
        max: 99999,
      },
    };
  },
  computed: {
    option() {
      return merge({}, this.basicOption, this.setting);
    },
  },
  methods: {
    //初始化函数
    imgLoad(msg) {
      // console.log('工具初始化函数=====' + msg);
    },
    refreshCrop() {
      this.$refs.cropper.refresh();
    },
    rotateLeft() {
      this.$refs.cropper.rotateLeft();
    },
    rotateRight() {
      this.$refs.cropper.rotateRight();
    },
    //实时预览函数
    realTime(data) {
      this.previews = data;
    },
    //选择图片
    selectImg(e) {
      let file = e.target.files[0];
      if (!/\.(jpg|jpeg|png|JPG|PNG)$/.test(e.target.value)) {
        this.$message({
          message: '图片类型要求：jpeg、jpg、png',
          type: 'error',
        });
        return false;
      }
      //转化为blob
      let reader = new FileReader();
      reader.onload = (e) => {
        let data;
        if (typeof e.target.result === 'object') {
          data = window.URL.createObjectURL(new Blob([e.target.result]));
        } else {
          data = e.target.result;
        }
        this.basicOption.img = data;
      };
      //转化为base64
      reader.readAsDataURL(file);
    },
    //上传图片
    uploadImg(type) {
      const { w = 0, h = 0 } = this.previews;
      if (this.option.limitSize !== false) {
        if (w > this.option.autoCropWidth) {
          this.$message.warn('图片宽度过宽，请重新裁剪！');
          return false;
        }
        if (h > this.option.autoCropHeight) {
          this.$message.warn('图片长度过长，请重新裁剪！');
          return false;
        }
      }
      if (type === 'blob') {
        //获取截图的blob数据
        this.$refs.cropper.getCropBlob(async (data) => {
          let formData = new FormData();
          formData.append('file', data, 'aa.png');
          formData.append('filePath', this.type);
          let res = await uploadFiles(formData);
          if (res && res.code == 200) {
            // 人脸验证
            if (this.faceCheck) {
              let result = await faceCheck({ image_url: res.data.url });
              if (!result || result.code != 200) {
                this.$message.warn(result.msg || '失败！');
                return false;
              }
            }
            this.$message.success(res.msg || '成功!');
            this.$emit('onSuccess', res.data.url);
            this.$emit('ok');
          } else {
            this.$message.warn(res.msg || '失败！');
          }
        });
      }
    },
  },
};
</script>

<style lang="less">
.cropper-content {
  .cropper-box {
    height: 300px;
  }
  .choose-img-btn-wrap {
    margin-bottom: 20px;
    .choose-img-btn {
      outline: none;
      display: inline-block;
      line-height: 1;
      white-space: nowrap;
      cursor: pointer;
      -webkit-appearance: none;
      text-align: center;
      -webkit-box-sizing: border-box;
      box-sizing: border-box;
      outline: 0;
      -webkit-transition: 0.1s;
      transition: 0.1s;
      font-weight: 500;
      padding: 8px 15px;
      font-size: 12px;
      border-radius: 3px;
      color: #fff;
      background-color: #409eff;
      border-color: #409eff;
      margin-right: 10px;
    }
  }
  .footer-btn {
    width: 100%;
    margin-top: 20px;
    display: flex;
    display: -webkit-flex;
    & > .ant-btn {
      margin-right: 10px;
    }
    .upload-btn {
      flex: 1;
      -webkit-flex: 1;
      display: flex;
      display: -webkit-flex;
      justify-content: flex-end;
    }
  }
}
</style>
